package com.nari.ncps.screen.service.impl.dryport;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.nari.ncps.screen.entity.dryport.DryportOpermonLocomotive;
import com.nari.ncps.screen.mapper.dryport.DryportOpermonLocomotiveMapper;
import com.nari.ncps.screen.service.dryport.DryportOpermonLocomotiveService;
import com.nari.ncps.screen.vo.dryport.LocomotiveDetailVO;
import com.nari.ncps.screen.vo.dryport.LocomotiveStatusVO;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 * 机车整体运行情况表 服务实现类
 * </p>
 *
 * @author xuesong
 * @since 2025-08-23
 */
@Service
public class DryportOpermonLocomotiveServiceImpl extends ServiceImpl<DryportOpermonLocomotiveMapper, DryportOpermonLocomotive> implements DryportOpermonLocomotiveService {

    @Override
    public LocomotiveStatusVO getLocomotiveStatus(Integer year, Integer month, Integer day) {
        // 默认查询昨天的数据
        LocalDate yesterday = LocalDate.now().minusDays(1);
        if (year == null) {
            year = yesterday.getYear();
        }
        if (month == null) {
            month = yesterday.getMonthValue();
        }
        if (day == null) {
            day = yesterday.getDayOfMonth();
        }
        
        // 查询指定日期的数据
        LambdaQueryWrapper<DryportOpermonLocomotive> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(DryportOpermonLocomotive::getYear, year);
        queryWrapper.eq(DryportOpermonLocomotive::getMonth, month);
        queryWrapper.eq(DryportOpermonLocomotive::getDay, day);
        queryWrapper.orderByAsc(DryportOpermonLocomotive::getSection)
                   .orderByAsc(DryportOpermonLocomotive::getVehicleType);

        List<DryportOpermonLocomotive> entityList = this.list(queryWrapper);
        
        LocomotiveStatusVO response = new LocomotiveStatusVO();
        
        // 如果没有数据，返回空对象
        if (entityList == null || entityList.isEmpty()) {
            response.setDataList(new ArrayList<>());
            return response;
        }
        
        // 从第一条数据获取总设备量（因为这个字段在每条记录中都是相同的）
        DryportOpermonLocomotive firstEntity = entityList.get(0);
        response.setTotalEquipment(firstEntity.getTotalEquipment());
        
        // 按机务段分组聚合数据
        Map<String, LocomotiveDetailVO> sectionMap = new HashMap<>();
        Map<String, List<Integer>> assignedMap = new HashMap<>();     // 存储每个段的配属数量列表
        List<String> allVehicleTypes = new ArrayList<>();             // 存储所有机车型号
        
        for (DryportOpermonLocomotive entity : entityList) {
            String section = entity.getSection();
            LocomotiveDetailVO detailVO = sectionMap.get(section);
            
            if (detailVO == null) {
                detailVO = new LocomotiveDetailVO();
                detailVO.setYear(entity.getYear());
                detailVO.setMonth(entity.getMonth());
                detailVO.setSection(section);
                detailVO.setInUse(0);
                detailVO.setStandby(0);
                detailVO.setOverhaul(0);
                detailVO.setMediumRepair(0);
                detailVO.setMinorRepair(0);
                detailVO.setTemporaryRepair(0);
                sectionMap.put(section, detailVO);
                assignedMap.put(section, new ArrayList<>());
            }
            
            // 收集所有机车型号到一维数组
            if (entity.getVehicleType() != null && !entity.getVehicleType().isEmpty()) {
                allVehicleTypes.add(entity.getVehicleType());
            }
            
            // 收集配属数量
            assignedMap.get(section).add(entity.getAssigned() != null ? entity.getAssigned() : 0);
            
            // 累加其他各项数据（不包括配属）
            detailVO.setInUse(detailVO.getInUse() + (entity.getInUse() != null ? entity.getInUse() : 0));
            detailVO.setStandby(detailVO.getStandby() + (entity.getStandby() != null ? entity.getStandby() : 0));
            detailVO.setOverhaul(detailVO.getOverhaul() + (entity.getOverhaul() != null ? entity.getOverhaul() : 0));
            detailVO.setMediumRepair(detailVO.getMediumRepair() + (entity.getMediumRepair() != null ? entity.getMediumRepair() : 0));
            detailVO.setMinorRepair(detailVO.getMinorRepair() + (entity.getMinorRepair() != null ? entity.getMinorRepair() : 0));
            detailVO.setTemporaryRepair(detailVO.getTemporaryRepair() + (entity.getTemporaryRepair() != null ? entity.getTemporaryRepair() : 0));
        }
        
        // 设置机车型号数组到顶层
        response.setVehicleType(allVehicleTypes);
        
        // 将配属数量用"+"连接
        for (Map.Entry<String, LocomotiveDetailVO> entry : sectionMap.entrySet()) {
            String section = entry.getKey();
            LocomotiveDetailVO detailVO = entry.getValue();
            
            // 连接配属数量
            List<Integer> assignedList = assignedMap.get(section);
            if (assignedList != null && !assignedList.isEmpty()) {
                detailVO.setAssigned(assignedList.stream()
                    .map(String::valueOf)
                    .collect(Collectors.joining("+")));
            }
        }
        
        // 转换为列表
        List<LocomotiveDetailVO> dataList = new ArrayList<>(sectionMap.values());
        response.setDataList(dataList);
        
        // 计算总配属和百分比
        int totalAssigned = 0;
        Integer baiyinhuaAssigned = null;
        Integer xigangkouAssigned = null;
        
        for (LocomotiveDetailVO detailVO : dataList) {
            // 将配属字符串（如"2+15+2"）拆分并求和
            if (detailVO.getAssigned() != null && !detailVO.getAssigned().isEmpty()) {
                String[] nums = detailVO.getAssigned().split("\\+");
                int sectionTotal = 0;
                for (String num : nums) {
                    sectionTotal += Integer.parseInt(num.trim());
                }
                totalAssigned += sectionTotal;
                
                if ("白音华机务段".equals(detailVO.getSection())) {
                    baiyinhuaAssigned = sectionTotal;
                } else if ("西港口机务段".equals(detailVO.getSection())) {
                    xigangkouAssigned = sectionTotal;
                }
            }
        }
        
        response.setTotalAssigned(totalAssigned);
        
        // 计算百分比（保留2位小数）
        if (totalAssigned > 0) {
            if (baiyinhuaAssigned != null) {
                response.setBaiyinhuaRatio(
                    new java.math.BigDecimal(baiyinhuaAssigned)
                        .multiply(new java.math.BigDecimal("100"))
                        .divide(new java.math.BigDecimal(totalAssigned), 2, java.math.RoundingMode.HALF_UP)
                );
            }
            if (xigangkouAssigned != null) {
                response.setXigangkouRatio(
                    new java.math.BigDecimal(xigangkouAssigned)
                        .multiply(new java.math.BigDecimal("100"))
                        .divide(new java.math.BigDecimal(totalAssigned), 2, java.math.RoundingMode.HALF_UP)
                );
            }
        }
        
        return response;
    }

}
